//
//  KZSeekScrollView.m
//  lg_zhinengbeikao_english
//
//  Created by 朱凯 on 2018/12/28.
//  Copyright © 2018 zhukai. All rights reserved.
//

#import "KZSeekScrollView.h"

@interface KZSeekScrollView()
/// 滑动方向
@property (nonatomic) int     scrollDirection;
/// 开始拖动滑动视图时，偏移的点，用于计算是往哪个方向滑动
@property (nonatomic) CGPoint scrollViewStartPosPoint;

@end

@implementation KZSeekScrollView

- (instancetype)init {
    if (self = [super init]) {
        self.scrollDirection = 0;
        self.delegate = self;
        self.pagingEnabled = true;
    }
    return self;
}

- (void)setMaxCount:(NSInteger)maxCount {
    
    _maxCount = maxCount;
    _currentIndex = 0;
    _itemViews = [[NSMutableDictionary alloc] init];
    
    [self layoutIfNeeded];
    
    CGFloat initialCount = _maxCount > 1 ? 2 : _maxCount;
    for (int i = 0; i < initialCount; i ++) {
        UIView *view = [self.dataSource seekScrollView:self viewAtIndex:i];
        view.frame = CGRectMake(i * self.width, 0, self.width, self.height);
        [self addSubview:view];
        _itemViews[[NSString stringWithFormat:@"%i", i]] = view;
    }
    self.contentSize = CGSizeMake(self.width * _maxCount, 0);
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    scrollView.scrollEnabled = false;
    
    
    if (decelerate) {
        self.scrollDirection =0;
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    
    NSInteger index = (NSInteger)(scrollView.contentOffset.x / scrollView.width);
    if (index == _currentIndex) {
        scrollView.scrollEnabled = true;
        return;
    } else {
        _currentIndex = index;
        [self seekToItemAtIndex:_currentIndex];
    }
    
    self.scrollDirection =0;
}

- (void)seekToItemAtIndex:(NSInteger)index {
    
    // 快捷取值
    CGFloat w = self.width;
    CGFloat h = self.height;
    
    // 选择快进到某题前的可视视图，可视视图会在创建完
    UIView *currentVisableView = _itemViews[[NSString stringWithFormat:@"%li", _currentIndex]];
    
    // 先把两侧的视图移除掉，仅保留现在可视的视图，用于滚动
    for (UIView *view in self.itemViews.allValues) {
        if (view != currentVisableView) {
            [view removeFromSuperview];
        }
    }
    
    // 记录当前要滑动到的位置的视图的引用
    UIView *indexView = nil;
    // 如果还未创建过，则创建
    if (_itemViews[[NSString stringWithFormat:@"%li", index]] == nil) {
        
        indexView = [self.dataSource seekScrollView:self viewAtIndex:index];
        [self addSubview:indexView];
        _itemViews[[NSString stringWithFormat:@"%li", index]] = indexView;
    }
    // 存在则直接获取
    else {
        indexView = _itemViews[[NSString stringWithFormat:@"%li", index]];
        [self addSubview:indexView];
    }
    // 设置frame，放到对应索引的位置去
    indexView.frame = CGRectMake(index * w, 0, w, h);
    
    // 如果点击试题快速跳转到某一题时，要假装从当前可视的视图滚动到目标视图，因此需要移动currentVisableView的位置并改变contentOffset，这样看起来就好像没有移动一样
    if (index == _currentIndex) {}
    else if (index > _currentIndex) {
        
        currentVisableView.frame = CGRectMake(indexView.left - w, 0, w, h);
        self.contentOffset = CGPointMake((index - 1) * w, 0);
        
    } else {
        
        currentVisableView.frame = CGRectMake(indexView.right, 0, w, h);
        self.contentOffset = CGPointMake((index + 1) * w, 0);
    }
    
    // 滚动动画：从当前可视的视图滚动到目标视图，index == _currentIndex是不需要滚动，时间设为0即可
    [UIView animateWithDuration:index == _currentIndex ? 0 : 0.35 animations:^{
        
        self.contentOffset = CGPointMake(index * w, 0);
        
    } completion:^(BOOL finished) {
        
        if (finished) {
            
            // 如果可视视图不是目标视图，则需要移除可视视图
            if (index != self->_currentIndex) {
                [currentVisableView removeFromSuperview];
            }
            
            // 目标视图的下一题索引和上一题序索引
            NSInteger nextIndex = index + 1;
            NSInteger prevIndex = index - 1;
            
            // 目标视图不是最后一题，则需要创建下一题
            if (nextIndex < self->_maxCount) {
                
                UIView *nextView = nil;
                if (self.itemViews[[NSString stringWithFormat:@"%li", nextIndex]] == nil) {
                    
                    nextView = [self.dataSource seekScrollView:self viewAtIndex:nextIndex];
                    [self addSubview:nextView];
                    self.itemViews[[NSString stringWithFormat:@"%li", nextIndex]] = nextView;
                }
                else {
                    nextView = self.itemViews[[NSString stringWithFormat:@"%li", nextIndex]];
                    [self addSubview:nextView];
                }
                nextView.frame = CGRectMake(indexView.right, 0, w, h);
            }
            
            // 目标视图不是第一题，则需要创建上一题
            if (prevIndex >= 0) {
                
                UIView *prevView = nil;
                if (self.itemViews[[NSString stringWithFormat:@"%li", prevIndex]] == nil) {
                    
                    prevView = [self.dataSource seekScrollView:self viewAtIndex:prevIndex];
                    [self addSubview:prevView];
                    self.itemViews[[NSString stringWithFormat:@"%li", prevIndex]] = prevView;
                }
                else {
                    prevView = self.itemViews[[NSString stringWithFormat:@"%li", prevIndex]];
                    [self addSubview:prevView];
                }
                prevView.frame = CGRectMake(indexView.left - w, 0, w, h);
            }
        }
        
        // 视图全部设置完毕，可滑动
        self.scrollEnabled = true;
        // 修改当前可视视图的索引
        self->_currentIndex = index;
    }];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (self.scrollDirection == 0){
        if (fabs(self.scrollViewStartPosPoint.x-scrollView.contentOffset.x)<
            fabs(self.scrollViewStartPosPoint.y-scrollView.contentOffset.y)){
            self.scrollDirection = 1;
        } else {
            self.scrollDirection = 2;
        }
    }
    if (self.scrollDirection == 1) {
        
        scrollView.contentOffset = CGPointMake(self.scrollViewStartPosPoint.x,scrollView.contentOffset.y);
    } else if (self.scrollDirection == 2){
        scrollView.contentOffset = CGPointMake(scrollView.contentOffset.x,self.scrollViewStartPosPoint.y);
    }
}
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    self.scrollViewStartPosPoint = scrollView.contentOffset;
    self.scrollDirection = 0;
}


@end
